package com.hfb.mashibing.alip8.jvm.jmm;

import com.hfb.mashibing.alip8.jvm.c0_basic.T;

public class T04_Disorder {

    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (;;) {
            i ++;
            x=0;y=0;
            a=0;b=0;
            Thread one = new Thread (new Runnable() {
                // 由于线程One先启动，羡慕这句话让它等待线程two，
                // 读者可以根据自己的电脑实际性能只当调整等待时间
                public void run(){
                    shortWait(100_0000);
                    a=1;
                    x=b;
                }
            });
            Thread other = new Thread (new Runnable() {
                // 由于线程One先启动，羡慕这句话让它等待线程two，
                // 读者可以根据自己的电脑实际性能只当调整等待时间
                public void run () {
                    b=1;
                    y=a;
                }
            });
            one.start();
            other.start();
            one.join();
            other.join();

            String res = String.format("第%s次（%s,%s)", i, x, y);
            if (x == 0 && y == 0) {
                // 只有乱序执行是才会出现（x，y）=（0，0）
                System.err.println(res);
                break;
            } else {
//                System.err.println(res);
            }

        }
    }

   private static void shortWait(int i) {
        try {
            Thread.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
